import dotenv from 'dotenv';
import { createServer } from './server';
import { getTerminalManager } from './controllers/terminalController';

dotenv.config();

const PORT = parseInt(process.env.PORT || '3001');
const HOST = process.env.HOST || '0.0.0.0';

const app = createServer();

const server = app.listen(PORT, HOST, () => {
  console.log(`🚀 Persistent Terminal API running on http://${HOST}:${PORT}`);
  console.log(`📝 API endpoint: http://${HOST}:${PORT}/api`);
  console.log(`❤️  Health check: http://${HOST}:${PORT}/api/health`);
});

const gracefulShutdown = async (signal: string) => {
  console.log(`\n${signal} received. Shutting down gracefully...`);
  
  server.close(() => {
    console.log('HTTP server closed');
  });

  try {
    const terminalManager = getTerminalManager();
    await terminalManager.shutdown();
    console.log('All terminals terminated');
    process.exit(0);
  } catch (error) {
    console.error('Error during shutdown:', error);
    process.exit(1);
  }
};

process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));

process.on('uncaughtException', (error) => {
  console.error('Uncaught Exception:', error);
  gracefulShutdown('UNCAUGHT_EXCEPTION');
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
